﻿#include "user_db.h"

user_db::user_db(QString db_name)
{
    user_data_all_name = USER_DATA_PATH+db_name;
    create_database("QSQLITE",user_data_all_name);
    user_sql_db = get_instance_db(user_data_all_name);
    create_table(user_sql_db,user_table_name,CREATE_USER);
}
int user_db::user_create_table(QString table_name)
{
    QString temp_order = CREATE_USER.replace(QString('*'),QString("%1").arg(table_name));
    int ret = create_table(user_sql_db,table_name,temp_order);
    qDebug()<<ret;
    return ret;
}
char user_db::user_login_check(QString login_name,QString login_password)
/*
 * 根据提供的用户信息，查找是否已经创建用户；
 * return:
 * true:存在同名用户
 * false:不存在同名用户
 */
{

    QSqlQuery query(user_sql_db);
    char val = -1;
    query.exec(SELECT_USER) ;
    while(query.next()){
        QString t_name = query.value(0).toString();
        QString t_password = query.value(1).toString();
        if(t_name == login_name ){
            val = 1;
            if(t_password == login_password)
                val = 2;
            return val;
        }
    }
    return val;
}
char user_db::user_insert_info(QString user_name, QString user_password)
/*
 * 插入用户信息；
 */
{
    char val = 0;
    if(user_login_check(user_name," ") >= 1) //创建之前就存在的话，就不能再创建
        val= I_EXIST ;
    else{
        QSqlQuery query(user_sql_db);
        QString temp_order = QString ("insert into user_info(name,password) values('%1','%2')").arg(user_name).arg(user_password);
        query.exec(temp_order);
        if(user_login_check(user_name,user_password) == 2) //创建好后需要再次查询验证,存在则创建成功
            val = I_SUCCESS;
        else
            val = I_FALSE;
    }
    return val;
}
